<template>
  <a-layout>
    <a-layout-content
        :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '680px' }"
    >
      <p>
        <a-form layout="inline" :model="nameParam">
          <a-form-item>
            <a-input v-model:value="nameParam.loginName" placeholder="输入要搜索的登录名"
                     @keyup.enter="handleQuery({page:1,size:pagination.pageSize,loginName:nameParam.loginName})"
                     size="large">
            </a-input>
          </a-form-item>
          <a-form-item>
            <a-button type="primary"
                      @click="handleQuery({page:1,size:pagination.pageSize,loginName:nameParam.loginName})"
                      size="large">搜索用户
            </a-button>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="add" size="large">新增用户</a-button>
          </a-form-item>
        </a-form>
      </p>
      <a-table
          :columns="columns"
          :row-key="record => record.id"
          :data-source="users"
          :pagination="pagination"
          :loading="loading"
          @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <span>
              <a-space size="small">
                <a-button type="primary" @click="edit(record)">编辑</a-button>
                <a-button type="primary" @click="resetPassword(record)">重置密码</a-button>
                <a-popconfirm
                    title="删除后不可恢复，确认删除?"
                    ok-text="是"
                    cancel-text="否"
                    @confirm="handleDelete(record.id)"
                >
                  <a-button type="primary" danger>删除</a-button>
                </a-popconfirm>
              </a-space>
            </span>
          </template>
        </template>
      </a-table>
    </a-layout-content>
  </a-layout>
  <a-modal
      v-model:visible="visible"
      title="用户表单"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      :ok-text=okText
      cancel-text="取消"
  >
    <a-form :model="user" :label-col="{ span: 6 }">
      <a-form-item label="登录名">
        <a-input v-model:value="user.loginName" :disabled="!!user.id"/>
      </a-form-item>
      <a-form-item label="昵称">
        <a-input v-model:value="user.name"/>
      </a-form-item>
      <a-form-item label="密码" v-show="!user.id">
        <a-input v-model:value="user.password" type="text"/>
      </a-form-item>
    </a-form>
  </a-modal>
  <a-modal
      v-model:visible="resetPasswordModelVisible"
      title="用户重置密码表单"
      :confirm-loading="resetPasswordModelLoading"
      @ok="handleResetPasswordModelOk"
      ok-text="提交"
      cancel-text="取消"
  >
    <a-form :model="user" :label-col="{ span: 6 }">
      <a-form-item label="新密码">
        <a-input v-model:value="user.password" type="text"/>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script lang="ts">
import {defineComponent, onMounted, ref} from 'vue';
import axios from "axios";
import {message} from "ant-design-vue";
import {Tool} from "@/util/tool";

//hexMd5、KEY存放在public，所以识别不到，需要声明一下
declare let hexMd5: any;
declare let KEY: any;

export default defineComponent({
  name: 'AdminUser',
  setup() {
    const users = ref();
    const user = ref();
    const nameParam = ref();
    nameParam.value = {};
    const pagination = ref({
      total: 0,
      current: 1,
      pageSize: 4
    });

    const loading = ref(false);

    const columns = [
      {
        title: '登录名',
        dataIndex: 'loginName',
        key: 'name',
      },
      {
        title: '昵称',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: '密码',
        dataIndex: 'password',
        key: 'password',
      },
      {
        title: 'Action',
        dataIndex: 'action',
        key: 'action'
      }
    ];

    /**
     * 数据查询
     */
    const handleQuery = (params: any) => {
      loading.value = true;
      axios.get("/user/list", {
        params: {
          page: params.page,
          size: params.size,
          loginName: params.loginName
        }
      }).then((response) => {
        loading.value = false;
        const data = response.data;
        if (data.success) {
          users.value = data.content.list;

          //重置分页按钮
          pagination.value.current = params.page;
          pagination.value.total = data.content.total;//有这个参数，前端才能计算出一共分成几页
        } else {
          message.error(data.message);
        }
      })
    }

    /**
     * 表格点击页码时触发
     */
    const handleTableChange = (pagination: any) => {
      handleQuery({
        page: pagination.current,
        size: pagination.pageSize,
        name: nameParam.value.loginName
      })
    }

    const visible = ref<boolean>(false);
    const confirmLoading = ref<boolean>(false);
    const okText = ref();

    /**
     * 编辑
     * @param record
     */
    const edit = (record: any) => {
      okText.value = "修改";
      visible.value = true;
      //复制一个新对象，这样进行编辑的时候，就不会修改表格数据了
      //user.value = record，这样写就和表格数据绑定了
      user.value = Tool.copy(record);
    }

    /**
     * 新增
     */
    const add = () => {
      okText.value = "新增";
      visible.value = true;
      user.value = {};
    }

    const handleDelete = (id: any) => {
      axios.delete("/user/delete/" + id).then((response) => {
        const data = response.data;
        if (data.success) {
          //重新加载列表
          handleQuery({
            page: pagination.value.current,
            size: pagination.value.pageSize
          })

          message.success("删除成功");
        }
      })
    }


    const handleOk = () => {
      confirmLoading.value = true;
      user.value.password = hexMd5(user.value.password + KEY);
      axios.post("/user/save", user.value).then((response) => {
        confirmLoading.value = false;
        const data = response.data;
        if (data.success) {
          visible.value = false;

          //重新加载列表
          handleQuery({
            page: pagination.value.current,
            size: pagination.value.pageSize
          })

          message.success(okText.value + "成功");
        } else {
          message.error(data.message);
        }
      })
    }

    const resetPasswordModelLoading = ref(false);
    const resetPasswordModelVisible = ref(false);

    const resetPassword = (record: any) => {
      resetPasswordModelVisible.value = true;
      //复制一个新对象，这样进行编辑的时候，就不会修改表格数据了
      //user.value = record，这样写就和表格数据绑定了
      user.value = Tool.copy(record);
      user.value.password = null;
    }

    const handleResetPasswordModelOk = () => {
      resetPasswordModelLoading.value = true;
      //对密码进行MD5加密
      user.value.password = hexMd5(user.value.password + KEY);
      axios.post("/user/resetPassword", user.value).then((response) => {
        resetPasswordModelLoading.value = false;
        const data = response.data;
        if (data.success) {
          resetPasswordModelVisible.value = false;

          //重新加载列表
          handleQuery({
            page: pagination.value.current,
            size: pagination.value.pageSize
          })

          message.success("重置密码成功");
        } else {
          message.error(data.message);
        }
      })
    }

    onMounted(() => {
      //查询用户
      handleQuery({
        page: 1,
        size: pagination.value.pageSize
      })
    })

    return {
      users,
      columns,
      pagination,
      loading,
      handleTableChange,
      visible,
      confirmLoading,
      edit,
      handleOk,
      user,
      add,
      okText,
      handleDelete,
      nameParam,
      handleQuery,
      handleResetPasswordModelOk,
      resetPasswordModelVisible,
      resetPasswordModelLoading,
      resetPassword
    };
  }
});
</script>
<style scoped>
.ant-avatar {
  width: 50px;
  height: 50px;
  line-height: 50px;
  border-radius: 8%;
  margin: 5px 0;
}
</style>
